package sealte.util.xml;

import java.io.FileOutputStream;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class XMLModifier {
	
	private String filePath = null;
	private Document doc = null;
	private Element root = null;
	
	public XMLModifier(String filePath){
		this.filePath = filePath;
		try {
			this.doc = XMLReader.getDocument(this.filePath);
			this.root = this.doc.getRootElement();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 重新设置属性(如果存在相同属性，会覆盖以前属性)
	 * @param attribute所属的Element路径
	 * @throws Exception
	 */
	public void setAttribute(String[] path,String name,String value) throws Exception {
		Element element = XMLReader.getElement(this.root, path);
		element.setAttribute(name, value);
	}
	
	public void removeAttribute(String[] path,String name) throws Exception {
		Element element = XMLReader.getElement(this.root, path);
		element.removeAttribute(name);
	}
	
	public void removeElement(String[] parentPath,String elementName) throws Exception {
		if(null==parentPath){
			this.doc.removeContent(this.doc.getRootElement());
		}else{
			Element parentElement = XMLReader.getElement(this.root,parentPath);
			parentElement.removeChild(elementName);
		}
	}
	
	public void removeElements(String[] parentPath,String elementName) throws Exception {
		Element parentElement = XMLReader.getElement(this.root,parentPath);
		parentElement.removeChildren(elementName);
	}
	
	public void addElement(String[] parentPath,String name,String value) throws Exception {
		Element parentElement = XMLReader.getElement(this.root, parentPath);
		parentElement.addContent(new Element(name).setText(value));
	}
	
	public void modifyElementText(String[] path,String newText) throws Exception {
		Element element = XMLReader.getElement(this.root, path);
		element.setText(newText);
	}
	
	public void reWrite() throws Exception {
		Format format = Format.getCompactFormat();
		format.setEncoding(XMLReader.getHeaderEncoding(this.filePath));
		format.setIndent("    ");
		XMLOutputter out = new XMLOutputter(format);
		out.output(doc, new FileOutputStream(this.filePath));
	}
	
}
